package com.club.chelseaclub.tab;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.club.chelseaclub.R;
import com.club.chelseaclub.util.SinaNewsRestClient;
import com.club.chelseaclub.view.XListView;
import com.club.chelseaclub.view.XListView.IXListViewListener;
import com.loopj.android.http.AsyncHttpResponseHandler;



public class Tab2Activity extends ListActivity implements IXListViewListener {
	Document doc;
	private int cpage = 2;
	private ProgressBar loading_progressBar;
	private XListView mListView;
	//private ArrayAdapter<String> mAdapter;
	private SimpleAdapter mAdapter;
	//private ArrayList<String> items = new ArrayList<String>();
	private ArrayList<Map<String, Object>> items = new ArrayList<Map<String,Object>>();
	private Handler mHandler;
	private int start = 0;
	private static int refreshCnt = 0;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qex_news_list);
//		geneItems();
		mListView = (XListView) findViewById(android.R.id.list);
		mListView.setPullLoadEnable(true);
		loading_progressBar = (ProgressBar) findViewById(R.id.loading_process_news_list);
		loadWebNews();
//		mAdapter = new SimpleAdapter(Tab2Activity.this,items,R.layout.news_list_item_all,
//	             new String[]{"title","date"},
//	             new int[]{R.id.title,R.id.date});;
//		mListView.setAdapter(mAdapter);
//		mListView.setPullLoadEnable(false);
//		mListView.setPullRefreshEnable(false);
		mListView.setXListViewListener(this);
		mHandler = new Handler();
	}

	private void geneItems() {
		for (int i = 0; i != 20; ++i) {
			Map<String, Object> map = new HashMap<String, Object>();
            map.put("title", "尔西与阿迪达斯续约10年尔西");
            map.put("date", "07-28 18:00");
            items.add(map);
			//items.add("refresh cnt " + (++start));
		}
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}
	
	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				cpage = 2;
				items.clear();
				//geneItems();
				// mAdapter.notifyDataSetChanged();
				//mAdapter = new ArrayAdapter<String>(Tab2Activity.this, R.layout.list_item, items);
//				mAdapter = new SimpleAdapter(Tab2Activity.this,items,R.layout.news_list_item_all,
//			             new String[]{"title","date"},
//			             new int[]{R.id.title});
//				mListView.setAdapter(mAdapter);
				loadWebNews();
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				//geneItems();
				String url = "http://sports.sina.cn/?sa=d2t10v417&cid=&cpage="+cpage+"&vt=4";
				//String url = "http://sports.sina.cn/?sa=d33864t12v2442&sid=&spage="+cpage+"&vt=4";
				SinaNewsRestClient.get(url, null, new AsyncHttpResponseHandler(){
					@Override
					public void onSuccess(String response) {
						Document doc = Jsoup.parse(response);
						Elements es = doc.getElementsByTag("li");
						String postDateStr = "";
						
						if(es.size() > 2) {
							for (int i=0; i<es.size() - 2; i++) {
								Element e = es.get(i);
								Map<String, Object> map = new HashMap<String, Object>();
								String postDate = e.getElementsByTag("div").text();
								if(postDate != null && !"".equals(postDate)){
									postDate = postDate.replaceAll("月", "/").replaceAll("日", "");
									postDateStr = postDate;
								}
								e.getElementsByTag("div").html("");
								map.put("title", e.getElementsByTag("li").text());
								map.put("date", postDateStr);
								map.put("url", e.getElementsByTag("a").attr("href")); 
								items.add(map);
							}
						}
						
						mAdapter.notifyDataSetChanged();
						cpage++;
						onLoad();
						
					}
					
					@Override
					public void onFailure(Throwable e, String response) {
						//通讯异常
						e.printStackTrace();
						//stopProgress(l, v, position);
						Log.d("===通信错误===", "通信错误response: " + response);
						Toast.makeText(getApplication(), "通信错误", Toast.LENGTH_SHORT).show();
					}
				});
				
			}
		}, 500);
	}
	
	private void loadWebNews() {
		String url = "http://sports.sina.cn/?sa=d2t10v417&cid=&cpage=1&vt=4";
		//String url = "http://sports.sina.cn/?sa=d33864t12v2442&sid=&spage=1&vt=4";
		SinaNewsRestClient.get(url, null, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String response) {
				Document doc = Jsoup.parse(response);
				Elements es = doc.getElementsByTag("li");
				String postDateStr = "";
				
				if(es.size() > 2) {
					for (int i=0; i<es.size() - 2; i++) {
						Element e = es.get(i);
						Map<String, Object> map = new HashMap<String, Object>();
						String postDate = e.getElementsByTag("div").text();
						if(postDate != null && !"".equals(postDate)){
							postDate = postDate.replaceAll("月", "/").replaceAll("日", "");
							postDateStr = postDate;
						}
						e.getElementsByTag("div").html("");
						map.put("title", e.getElementsByTag("li").text());
						map.put("date", postDateStr);
						map.put("url", e.getElementsByTag("a").attr("href")); 
						items.add(map);
					}
				}
				
				mAdapter = new SimpleAdapter(Tab2Activity.this,items,R.layout.news_list_item_all,
			             new String[]{"title","date","url"},
			             new int[]{R.id.title,R.id.date});
				mListView.setAdapter(mAdapter);
				
				loading_progressBar.setVisibility(View.GONE);
				
			}
			
			@Override
			public void onFailure(Throwable e, String response) {
				//通讯异常
				e.printStackTrace();
				//stopProgress(l, v, position);
				Log.d("===通信错误===", "通信错误response: " + response);
				Toast.makeText(getApplication(), "通信错误", Toast.LENGTH_SHORT).show();
			}
		});
		
		/*
		try {
			doc=Jsoup.parse(new URL("http://www.cnbeta.com"), 5000);
			Log.i("AAAAAAAAAA",doc.toString());
			} catch (MalformedURLException e1) {
			  e1.printStackTrace();
			} catch (IOException e1) {
			  e1.printStackTrace();
			}
			//List<Map<String,String>> list = new ArrayList<Map<String, String>>();
			Elements es = doc.getElementsByClass("topic");
			for (Element e : es) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("title", e.getElementsByTag("a").text());
				map.put("date", "http://www.cnbeta.com" + e.getElementsByTag("a").attr("href")); 
				items.add(map);
			}
			
			mAdapter = new SimpleAdapter(Tab2Activity.this,items,R.layout.news_list_item_all,
		             new String[]{"title","date"},
		             new int[]{R.id.title,R.id.date});;
			mListView.setAdapter(mAdapter);
		 */
	}
	
	//重写onListItemClick但是ListView条目事件
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
	 // TODO Auto-generated method stub
		 super.onListItemClick(l, v, position, id);
		 int newsInt = position - 1;
		 Object newsDetailUrl = items.get(newsInt).get("url");
		 String url = (String) newsDetailUrl;
		 
		 Intent intent = new Intent();
	     intent.putExtra("url", url);
	     intent.setClass(Tab2Activity.this, NewsDetailActivity.class);
	     
	     startActivity(intent);
		 
		 //显示单击条目ID号
		 System.out.println("id = "+ id);
		 //显示所单击条目的位置数
		 System.out.println("position = "+ position);
	}

}
